/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/subtree-with-maximum-average
   @Language: C++
   @Datetime: 19-04-08 14:24
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	pair<int,int> dfs(TreeNode *root,TreeNode **node, double &maxavg){
		if(root==NULL) return {0,0};
		auto left=dfs(root->left,node,maxavg), right=dfs(root->right,node,maxavg);
		int sum=left.first+right.first+root->val;
		int count=left.second+right.second+1;
		if(sum*1.0/count>maxavg){
			maxavg=sum*1.0/count;
			*node=root;
		}
		return {sum,count};
	}
public:
	/**
	 * @param root: the root of binary tree
	 * @return: the root of the maximum average of subtree
	 */
	TreeNode * findSubtree2(TreeNode * root) {
		// write your code here
		TreeNode *node=NULL;
		double maxavg=INT_MIN;
		dfs(root,&node,maxavg);
		return node;
	}
};
